<?php

class Model_Marker
{

    protected $_table;

    public function getTable()
    {
        if (null === $this->_table) {
            require_once APPLICATION_PATH . '/models/DbTable/Marker.php';
            $this->_table = new Model_DbTable_Marker;
        }
        return $this->_table;
    }
    
    public function save(array $data)
    {
        $table  = $this->getTable();
        $fields = $table->info(Zend_Db_Table_Abstract::COLS);
        foreach ($data as $field => $value) {
            if (!in_array($field, $fields)) {
                unset($data[$field]);
            }
        }
        return $table->insert($data);
    }
    
    public function fetchEntries()
    {
        return $this->getTable()->fetchAll('1')->toArray();
    }
    public function fetchByGroupId($group_id)    
    {
        $table = $this->getTable();
        $select = $table->select()->where('group_id = ?', $group_id);
        return $table->fetchAll($select)->toArray();
    }
    public function fetchEntry($id)
    {
        $table = $this->getTable();
        $select = $table->select()->where('id = ?', $id);
        return $table->fetchRow($select)->toArray();
    }
    
    public function saveMarkers($group, $group_id){
        $table = $this->getTable();
        foreach($group as $g){
            foreach($g as $locKey => $locValue){
                $select = $table->select()
                                ->where('timestamp = ?', $locValue['ts'])
                                ->where('group_id = ?', $group_id);
                unset($row);
                $row = $table->fetchRow($select);
                if(!isset($row)){
                    $row = $table->createRow();
                    $row->timestamp = $locValue['ts'];
                    $row->latitude = $locValue['lat'];
                    $row->longitude = $locValue['lng'];
                    $row->altitude = $locValue['alt'];
                    $row->name = $locValue->Desc;
                    $row->group_id = $group_id;
                    $row->save();
                }
            }
        }        
    }
}
